package cn.com.homeyoda.aimate.aihealth.ui.videoinspect;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.video.FileOutputOptions;
import androidx.camera.video.Quality;
import androidx.camera.video.QualitySelector;
import androidx.camera.video.Recorder;
import androidx.camera.video.Recording;
import androidx.camera.video.VideoCapture;
import androidx.camera.video.VideoRecordEvent;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.util.Pair;
import androidx.databinding.library.baseAdapters.BR;
import androidx.lifecycle.ViewModelProviders;

import com.google.android.material.datepicker.MaterialDatePicker;
import com.google.common.util.concurrent.ListenableFuture;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.com.homeyoda.aimate.aihealth.R;
import cn.com.homeyoda.aimate.aihealth.app.AppViewModelFactory;
import cn.com.homeyoda.aimate.aihealth.base.BaseFragment;
import cn.com.homeyoda.aimate.aihealth.databinding.FragmentVideoInspectBinding;
import cn.com.homeyoda.aimate.aihealth.ui.MainActivity;
import cn.com.homeyoda.aimate.aihealth.ui.bluetooth.BluetoothSearchActivity;
import cn.com.homeyoda.aimate.aihealth.ui.health.VideoPlayActivity;
import cn.com.homeyoda.aimate.aihealth.utils.LoadingStateManager;
import cn.com.homeyoda.aimate.aihealth.utils.ShowIsAuthDialog;
import cn.com.homeyoda.aimate.aihealth.utils.ShowLoadingDialog;
import cn.com.homeyoda.aimate.aihealth.utils.ShowLoadingUtil;


public class VideoInspectFragment extends BaseFragment<FragmentVideoInspectBinding, VideoInspectModel> {

    private static final int PERMISSIONS_REQUEST_CODE = 100;

    private ExecutorService cameraExecutor;
    private VideoCapture<Recorder> videoCapture;
    private ProcessCameraProvider cameraProvider;
    private Recording recording;
    private ObjectAnimator rotationAnimator;
    private File file;
    private static final long TOTAL_TIME = 15000; // 15秒倒计时
    private static final long INTERVAL = 1000; // 1秒更新一次
    private ShowLoadingDialog showLoadingDialog;
    String deviceId = "";
    String videoUrl = "";
    long seconds = 100;
    @Override
    public VideoInspectModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(VideoInspectModel.class);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void initData() {
        super.initData();
        initView();
        viewModel.deviceIsAuth(Build.SERIAL);
        viewModel.requestData();
        viewModel.getDeviceId(Build.SERIAL);
        observeLoadingState();
    }

    private void initView() {
        // 旋转动画
//        rotationAnimator = ObjectAnimator.ofFloat(binding.loading, "rotation", 0f, 360f);
//        rotationAnimator.setDuration(1500); // 1 秒
//        rotationAnimator.setRepeatCount(ObjectAnimator.INFINITE); // 无限循环
//        rotationAnimator.start();
        binding.start.setClickable(false);
        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        binding.record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

//                Intent intent = new Intent(getContext(), TiJianRecordActivity.class);
//                intent.putExtra("deviceId", deviceId);
//                startActivity(intent);
                Intent intent = new Intent(getContext(), BluetoothSearchActivity.class);
                intent.putExtra("deviceId", deviceId);
                startActivity(intent);
            }
        });

        binding.tipvideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if(binding.video.getVisibility() == View.VISIBLE){
//                    binding.video.onVideoPause();
//                    binding.video.setVisibility(View.GONE);
//                }else{
//                    binding.video.setVisibility(View.VISIBLE);
//                }
                Intent intent = new Intent(getContext(), VideoPlayActivity.class);
                intent.putExtra("videoUrl", videoUrl);
                startActivity(intent);

            }
        });

        binding.start.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onClick(View view) {
                startRecording();
                startTimer();
                startCountdown();
                binding.tipvideo.setClickable(false);
                binding.record.setClickable(false);
                binding.start.setClickable(false);

//                Toast.makeText(VideoInspectFragment.this, "保持不动10秒钟", Toast.LENGTH_SHORT).show();
            }
        });
        ImageView fullscreenButton = binding.video.findViewById(com.shuyu.gsyvideoplayer.R.id.fullscreen);
        if (fullscreenButton != null) {
            fullscreenButton.setVisibility(View.GONE);
        }

        ImageView backButton = binding.video.findViewById(com.shuyu.gsyvideoplayer.R.id.back);
        if (backButton != null) {
            backButton.setVisibility(View.GONE);
        }

        binding.video.setVideoAllCallBack(new GSYSampleCallBack() {
            @Override
            public void onAutoComplete(String url, Object... objects) {
                // 视频正常播放完成时调用
                Log.d("GSYVideoPlayer", "视频播放完成");
                binding.video.setVisibility(View.GONE);

                // 可以在这里添加自动播放下一集等逻辑
            }

            @Override
            public void onPlayError(String url, Object... objects) {
                // 播放出错时调用
                Log.e("GSYVideoPlayer", "播放错误");
            }
        });

    }









    private void startCountdown() {
        new CountDownTimer(TOTAL_TIME, INTERVAL) {
            @Override
            public void onTick(long millisUntilFinished) {
                // 每秒更新UI
                long secondsRemaining = millisUntilFinished / 1000;
                binding.start.setText("体检中"+String.valueOf(secondsRemaining)+"s");
                seconds = secondsRemaining;
            }

            @Override
            public void onFinish() {
                binding.start.setText("上传中");
                // 倒计时结束后的操作
            }
        }.start();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void startCamera() {
//
        ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(getActivity());

        cameraProviderFuture.addListener(() -> {
            try {
                cameraProvider = cameraProviderFuture.get();
                Preview preview = new Preview.Builder().build();
                preview.setSurfaceProvider(binding.preview.getSurfaceProvider());

                Recorder recorder = new Recorder.Builder()
                        .setQualitySelector(QualitySelector.from(Quality.HIGHEST))
                        .build();
                videoCapture = VideoCapture.withOutput(recorder);


                CameraSelector cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA;

                cameraProvider.unbindAll();
                Camera camera = cameraProvider.bindToLifecycle(
                        this, cameraSelector, preview, videoCapture);
                // 监听预览状态
                binding.preview.getPreviewStreamState().observe(this, streamState -> {
                    if (streamState == PreviewView.StreamState.STREAMING) {
                        // 预览流已启动，隐藏加载动画
                        binding.loading.setVisibility(View.GONE);
                        binding.loading2.setVisibility(View.GONE);
                        binding.start.setClickable(true);
                        //binding.chushihua.setVisibility(View.GONE);
                        //rotationAnimator.cancel();
                    } else if (streamState == PreviewView.StreamState.IDLE) {
                        // 预览流未启动，显示加载动画

                    }
                });
            } catch (ExecutionException | InterruptedException e) {
                //rotationAnimator.cancel();
                Log.e("CameraXApp", "Use case binding failed", e);
            }
        }, ContextCompat.getMainExecutor(getActivity()));
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void startRecording() {
        if (videoCapture == null) {
            return;
        }
        if (recording != null) {
            recording.stop();
            recording.close();
            recording = null;
        }
        File videoFile = new File(getActivity().getExternalFilesDir(null), "video.mp4");
        recording = videoCapture.getOutput()
                .prepareRecording(getActivity(), new FileOutputOptions.Builder(videoFile).build())
                .start(ContextCompat.getMainExecutor(getContext()), videoRecordEvent -> {
                    if (videoRecordEvent instanceof VideoRecordEvent.Start) {
                        //recordButton.setText("Stop Recording");
                    } else if (videoRecordEvent instanceof VideoRecordEvent.Finalize) {
                        if (!((VideoRecordEvent.Finalize) videoRecordEvent).hasError()) {
                            Log.i("huazai","videopath==="+videoFile.getAbsolutePath());
                            if(seconds<1){
                                binding.tipvideo.setClickable(true);
                                binding.record.setClickable(true);
                                Intent intent = new Intent(getContext(), TiJianResultActivity.class);
                                intent.putExtra("file_path", videoFile.getAbsolutePath());
                                intent.putExtra("deviceId", deviceId);
                                startActivity(intent);
                            }

                            //startActivity(new Intent(getContext(), TiJianResultActivity.class));
                        } else {
                            Log.i("haha","videopath===hasError");
                            if(this.recording != null){
                                this.recording.close();
                                this.recording = null;
                            }


                        }
                        //recordButton.setText("Start Recording");
                    }
                });

        //this.recording = recording;
    }



    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void stopRecording() {
        if (recording != null) {
            recording.stop();
            recording.close();
            recording = null;
        }


    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onPause() {
        super.onPause();
        if(cameraProvider != null){
            cameraProvider.unbindAll(); // 释放相机资源
        }
        stopRecording();
        if(cameraExecutor != null){
            cameraExecutor.shutdown();
        }
        Log.i("haha","onPause===");
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onResume() {
        super.onResume();
        Log.i("huahua","onResume===");
        if(allPermissionsGranted()){
            cameraExecutor = Executors.newSingleThreadExecutor();

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                startCamera();
            }

        }else{
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.RECORD_AUDIO},
                    PERMISSIONS_REQUEST_CODE);
            Log.i("huahua","onResume==else=");
        }
        binding.start.setText("开始体验");
    }

    //    private void startVideo(){
//        File outputDir = getExternalFilesDir(Environment.DIRECTORY_MOVIES);
//        File videoFile = new File(outputDir, "video.mp4");
//        binding.cameraview.takeVideo(videoFile, 10000); // 录制10秒
//    }
//
//    private void stopVideo(){
//        if (binding.cameraview.isTakingVideo()) {
//            binding.cameraview.stopVideo();
//        }
//    }

    private void startTimer() {
        new Handler().postDelayed(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void run() {
                stopRecording(); // 停止录制视频
            }
        }, 15000); // 15秒后停止录制（10000毫秒）
    }

    private boolean allPermissionsGranted() {
        String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.RECORD_AUDIO};
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (recording != null) {
            recording.stop();
            recording.close();
            recording = null;
        }

        Log.i("haha","onDestroy===");

    }

    private void observeLoadingState() {
        LoadingStateManager.getInstance().getLoadingState()
                .observe(this, isLoading -> {
                    if (isLoading) {
                        showLoadingDialog();
                    } else {
                        hideLoadingDialog();
                    }
                });
    }

    protected void showLoadingDialog() {
        // 实现你的加载对话框显示逻辑
        ShowLoadingUtil.showLoading(getContext());
    }

    protected void hideLoadingDialog() {
        // 实现你的加载对话框隐藏逻辑
        ShowLoadingUtil.dismiss();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.i("huage","onRequestPermissionsResult==requestCode="+requestCode);
        if (requestCode == PERMISSIONS_REQUEST_CODE) {
            if (allPermissionsGranted()) {
                cameraExecutor = Executors.newSingleThreadExecutor();
//                binding.container.post(() -> {
//                    startCamera();
//                });
                startCamera();
            } else {
                MainActivity.mainActivity.finish();
            }
        }
    }

    @Override
    public void initViewObservable() {
        viewModel.stateVideoUrlData.observe(this,url -> {
            Log.i("huahua","url====="+url);
            videoUrl = url;
            // 设置播放源
//            binding.video.setUp(url, true, "体检引导");
//
//            // 设置返回键
//            binding.video.getBackButton().setVisibility(View.VISIBLE);
//            // 以下设置可以阻止自动播放
//            binding.video.setPlayTag("video");
//            binding.video.setPlayPosition(-1);
        });
        viewModel.deviceIsAuthData.observe(this,deviceIsAuthBean -> {
            if(deviceIsAuthBean.getCode()==200){

            }else if(deviceIsAuthBean.getCode()==500){
                ShowIsAuthDialog showIsAuthDialog = new ShowIsAuthDialog(getContext(),deviceIsAuthBean.getMsg(),
                        deviceIsAuthBean.getData().getProductLink(),deviceIsAuthBean.getData().getCustomerService());
                showIsAuthDialog.Show();
                //Toast.makeText(getContext(),deviceIsAuthBean.getMsg(),Toast.LENGTH_SHORT).show();
            }
        });
        viewModel.deviceIdData.observe(this,deviceIdBean -> {
            deviceId = deviceIdBean.getData();
        });

    }



    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_video_inspect;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }
}
